//
//  RTRefreshControl.swift
//  Weibo
//
//  Created by Brisinga on 16/3/9.
//  Copyright © 2016年 Root. All rights reserved.
//

import UIKit
import SnapKit

enum RTRefreshState: Int {
    
    case Normal = 0,Pulling,Refreshing
}

// 控件高度
private let refreshH: CGFloat = 50

class RTRefreshControl: UIControl {
    
    
    var refreshState: RTRefreshState = .Normal{
    
        didSet {
            
            switch refreshState {
            
            case.Pulling:
                print("进入松手就刷新的状态")
                
                messageLabel.text = "放开起飞"
                
                UIView.animateWithDuration(0.2, animations: { () -> Void in
                    
                    self.imageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case.Normal:
                
                print("默认状态")
                
                imageView.hidden = false
                activity.stopAnimating()
                
                messageLabel.text = "下拉继续飞起"
                
                UIView.animateWithDuration(0.2, animations: { () -> Void in
                    
                    self.imageView.transform = CGAffineTransformIdentity
                })
                
                if oldValue == .Refreshing {
                
                    UIView.animateWithDuration(0.2, animations: { () -> Void in
                        
                        self.scrollView?.contentInset.top -= refreshH
                    })
                }
                
            case.Refreshing:
                
                print("别tm拉了,正在飞呢")
                
                imageView.hidden = true
                activity.startAnimating()
                
                messageLabel.text = "正在飞呢"
                
                UIView.animateWithDuration(0.2, animations: { () -> Void in
                    
                    self.scrollView?.contentInset.top += refreshH
                })
                
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
            }
        
        
        }
    
    }
    
    
    //构造方法
   override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 加载内部方法
        setupUI()
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    
    
    // 加载内部方法
    private func setupUI() {
        
        self.backgroundColor = UIColor.darkGrayColor()
        
        frame.size = CGSize(width: kScreenWidth, height: refreshH)
        
        frame.origin.y = -refreshH
        
        
        addSubview(activity)
        addSubview(messageLabel)
        addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        activity.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(imageView)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerY.equalTo(imageView)
            make.leading.equalTo(imageView.snp_trailing)
        }
        
    }
    
    
    
    // 将要添加到某个父控件的时候
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        if let scrollView  = newSuperview as? UIScrollView {
        
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.Old,.New], context: nil)
            
            self.scrollView = scrollView
        
        }
    }
    
    
    // 当当前控件观察的对象身上某个属性发生改变的时候会调用
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        // scrollView初始偏移量
        let contentTop = scrollView!.contentInset.top
        
        //y 方向的偏移量
        let contentY = scrollView!.contentOffset.y
        
        
        let contentValue = -contentTop - refreshH
        
        
        if scrollView!.dragging {
        
            if contentY <= contentValue && refreshState == .Normal {
                
                print("松手我就飞了")
                
                refreshState = .Pulling
                
            }else if contentY > contentValue && refreshState == .Pulling{
                
                
                print("我还没飞")
                
                refreshState = .Normal
                
            }
        
        }else {
            
            if refreshState == .Pulling {
                
                print("老子在飞")
                refreshState = .Refreshing
                
            }
            
        }

        
        
    }
    
    
    func endRfreshing() {
    
        refreshState = .Normal
    }
    
     weak var scrollView: UIScrollView?
    
    // 移除监听者
    deinit {
    
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
  
    // 懒加载
    private lazy var imageView:UIImageView = {
    
        let imageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
        
        return imageView
    }()
    
    
    private lazy var messageLabel: UILabel = {
    
        let messageLabel = UILabel(textColor: UIColor.lightGrayColor(), textFont: 14)
        
        messageLabel.text = "刷的飞起"
        
        return messageLabel
        
    }()
    
    
    private lazy var activity: UIActivityIndicatorView = {
    
        let activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
        
        
        return activity
    }()
}
